import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/note_provider.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_button.dart';
import 'package:go_router/go_router.dart';
import '../../../domain/entities/note.dart';
// 添加请求实体导入

/// 笔记详情页面
class NoteDetailPage extends ConsumerStatefulWidget {
  final int noteId;

  const NoteDetailPage({super.key, required this.noteId});

  @override
  ConsumerState<NoteDetailPage> createState() => _NoteDetailPageState();
}

class _NoteDetailPageState extends ConsumerState<NoteDetailPage> {
  @override
  void initState() {
    super.initState();
    // 加载笔记详情
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(noteStateProvider.notifier).loadNote(widget.noteId);
    });
  }

  @override
  Widget build(BuildContext context) {
    final noteState = ref.watch(noteStateProvider);
    final currentNote = ref.watch(currentNoteProvider);

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('笔记详情'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          if (currentNote != null)
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: () {
                // 跳转到编辑页面
                context.push('/admin/notes/${widget.noteId}/edit');
              },
            ),
          if (currentNote != null)
            PopupMenuButton<String>(
              onSelected: (value) {
                if (value == 'delete') {
                  _confirmDelete(context);
                }
              },
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'delete',
                  child: ListTile(
                    leading: Icon(Icons.delete, color: Colors.red),
                    title: SelectableText('删除笔记'),
                  ),
                ),
              ],
            ),
        ],
      ),
      body: _buildContent(noteState, currentNote),
    );
  }

  /// 构建页面内容
  Widget _buildContent(NoteState state, Note? note) {
    if (state is NoteLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (state is NoteError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            SelectableText('加载失败: ${state.message}'),
            const SizedBox(height: 16),
            AdaptiveButton(
              onPressed: () {
                ref.read(noteStateProvider.notifier).loadNote(widget.noteId);
              },
              child: const SelectableText('重新加载'),
            ),
          ],
        ),
      );
    }

    if (note == null) {
      return const Center(
        child: SelectableText('笔记不存在'),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和类型
          Row(
            children: [
              Expanded(
                child: SelectableText(
                  note.title,
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12.0,
                  vertical: 6.0,
                ),
                decoration: BoxDecoration(
                  color: _getNoteTypeColor(note.noteType),
                  borderRadius: BorderRadius.circular(16.0),
                ),
                child: SelectableText(
                  note.noteType.description,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 标签
          Wrap(
            spacing: 8.0,
            runSpacing: 8.0,
            children: note.tags.map((tag) {
              return Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12.0,
                  vertical: 6.0,
                ),
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(16.0),
                  border: Border.all(
                    color: Colors.blue.withOpacity(0.3),
                  ),
                ),
                child: SelectableText(
                  tag,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.blue,
                  ),
                ),
              );
            }).toList(),
          ),
          const SizedBox(height: 24),

          // 内容
          AdaptiveCard(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SelectableText(
                  '内容',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 16),
                SelectableText(
                  note.content,
                  style: const TextStyle(fontSize: 16),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),

          // 元信息
          AdaptiveCard(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SelectableText(
                  '信息',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 16),
                _buildInfoRow('创建时间', _formatDate(note.createTime)),
                const SizedBox(height: 8),
                _buildInfoRow('更新时间', _formatDate(note.updateTime)),
                const SizedBox(height: 8),
                _buildInfoRow('关联项目',
                    note.projectId != null ? '#${note.projectId}' : '无'),
                const SizedBox(height: 8),
                _buildInfoRow(
                    '关联任务', note.todoId != null ? '#${note.todoId}' : '无'),
                const SizedBox(height: 8),
                _buildInfoRow('作者ID', '#${note.authorId}'),
                const SizedBox(height: 8),
                _buildInfoRow('公开状态', note.isPublic ? '公开' : '私有'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      children: [
        SizedBox(
          width: 80,
          child: SelectableText(
            label,
            style: const TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: SelectableText(
            value,
            style: const TextStyle(fontSize: 14),
          ),
        ),
      ],
    );
  }

  /// 获取笔记类型颜色
  Color _getNoteTypeColor(NoteType type) {
    switch (type) {
      case NoteType.meeting:
        return Colors.orange;
      case NoteType.solution:
        return Colors.green;
      case NoteType.issue:
        return Colors.red;
      default:
        return Colors.blue;
    }
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}';
  }

  /// 确认删除
  void _confirmDelete(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: const SelectableText('确定要删除这个笔记吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const SelectableText('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 执行删除操作
              ref
                  .read(noteStateProvider.notifier)
                  .deleteNote(widget.noteId)
                  .then((_) {
                // 删除成功后返回上一页
                context.pop();
              });
            },
            child:
                const SelectableText('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}
